from . import *

from user.views import commo


@require_GET
def user_search_data(request):
    """按照条件进行数据查询，返回分页数据"""
    try:
        pagesize = request.GET.get("pagesize")
        values = (
            'id', 'user_name', 'job_num', 'real_name', 'dep', 'tel', 'group',
            'status')
        filters = {'status__in': [1, 2]}
        # 数据分页
        paginator_data = data_search.limit_data_paginator(
            request, User, values=values, pagesize=pagesize, **filters)

        return restful.ok(message='ok', data=paginator_data)
    except Exception as e:
        log_print(waring=traceback.format_exc())
        return restful.server_error(message=RETURN_MESSAGE)


def user_excel_download(request):
    """用户信息表格下载"""
    try:
        user_head_data = {
            # sheet第一行head名、列宽值, 按照前端数据展示顺序
            '序号': 6,  # 单独设置
            '用户名': 10,  # 与errorLog_values对应上path
            '真实姓名': 10,
            '工号': 20,
            '部门': 15,
            '电话': 16,
            '角色': 10,
            '状态': 10,
        }
        # 数据查询显示字段值以及顺序，顺序与对应sheetHeadData
        user_sheet_data = (
            'user_name', 'real_name', 'job_num', 'dep', 'tel', 'group',
            'status'
        )
        filters = {'status__in': [1, 2]}
        excel_data = data_search.orm_data_search(
            request, User, values=user_sheet_data,
            **filters)
        # 更新汉字信息
        for i in excel_data:
            i['group'] = User.GROUP(i['group']).name
            i['status'] = User.STATUS(i['status']).name
        excel_download = attachment.excel_export(
            request, excel_data=excel_data, filename='用户信息表.xlsx',
            sheet_name='用户信息', sheet_head_data=user_head_data)
        return excel_download
    except Exception as e:
        log_print(waring=traceback.format_exc())
        return restful.server_error(message=RETURN_MESSAGE)


@require_GET
def user_group_name(request):
    """下拉框角色数据填充"""
    try:
        data1 = ['管理员', '车辆调度员']
        # 列表解析返回下拉框数据 [{'value': 0, 'label': '管理员'}... ]
        data = [{'group': x, 'label': x} for x in data1]
        return restful.ok(data=data)
    except Exception as e:
        log_print(waring=traceback.format_exc())
        return restful.server_error(message=RETURN_MESSAGE)


@require_POST
def user_status_change(request):
    """用户信息[启用/禁用]更改，修改【status】字段"""
    try:
        user_id = json.loads(request.body)['id']
        status = int(json.loads(request.body)['status'])
        User.objects.filter(pk=user_id).update(status=status)
        return restful.ok(message='该账号已{}!'.format(User.STATUS(status).name))
    except Exception as e:
        log_print(waring=traceback.format_exc())
        return restful.server_error(message=RETURN_MESSAGE)
